# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from borrow_card.forms import BorrowCardApplyForm
from db.models import db, User, BorrowCard, BorrowBook
from permission_control import permission_required
from const import BorrowCardApplyStatus, PERMISSION
from datetime import datetime
from dateutil.relativedelta import relativedelta
from sqlalchemy import func
from config import app

borrow_card_blueprint = Blueprint('user_card', __name__)


@borrow_card_blueprint.route('/user_card', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BORROW_CARD_APPLY.KEY)
def card_view():
    form = BorrowCardApplyForm()
    if request.method == 'GET':
        borrow_card = BorrowCard.query.filter_by(user_id=current_user.id).first()
        borrow_book_count = BorrowBook.query.filter_by(user_id=current_user.id).count()
        overdue_book_count = BorrowBook.query.filter_by(user_id=current_user.id, is_return=0, is_overdue=1).count()
        form = BorrowCardApplyForm()
        return render_template('user_card/card_view.html',
                               form=form, 
                               borrow_card=borrow_card, 
                               borrow_book_count=borrow_book_count,
                               overdue_book_count=overdue_book_count)
    else:
        
        if form.validate_on_submit():
        
            # user = User.query.filter_by(id=current_user.id)
            user = current_user
            age = datetime.now().year - form.birthday.data.year
            
            user.age = age
            user.gender = form.gender.data
            user.birthday = form.birthday.data
            user.user_idcard = form.user_idcard.data
            user.user_phone = form.user_phone.data
            user.borrow_card_apply_status = BorrowCardApplyStatus.APPLYING.value
            print(f"user: {user}")
            # db.session.add(user)
            db.session.commit()
            form.populate_obj(user)
            flash('借阅卡已提交申请！', 'success')
        else:
            flash(f'借阅卡提交申请失败！{form.errors}', 'danger')
        return redirect(url_for('user_card.card_view'))
    
